// 登入组件
import React from "react";
import { Button, Form, Input, message } from "antd";
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import {Link, useNavigate} from 'react-router-dom'
import "./less/Login.less";
import logoImg from "../assets/images/logo.png";
import {LoginApi} from '../utils/request/api'

export default function Login() {
  const navigate = useNavigate()
  const onFinish = (values) => {
    console.log("Success:", values);
    LoginApi({
      username: values.username,
      password: values.password
    }).then(res=>{
      if(res.errCode === 0){
        message.success(res.message)
        // 存储数据
        localStorage.setItem('avatar',res.data.avatar)//头像
        localStorage.setItem('cms-token',res.data['cms-token'])//token
        localStorage.setItem('editable',res.data.editable)//是否可编辑
        localStorage.setItem('player',res.data.player)//用户判断
        localStorage.setItem('username',res.data.username)//用户名
        // 跳转到根路径
        setTimeout(()=>navigate('/'),1000)
      }else{
        message.error(res.message)
      }
    })
  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
    message.error('登录失败');
  };
  return (
    <div className="login">
      <div className="login_box">
        <img src={logoImg} alt="" />
        <Form
          name="basic"
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="Username"
            name="username"
            rules={[
              {
                required: true,
                message: "请输入用户名!",
              },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="请输入用户名"/>
          </Form.Item>
          <Form.Item
            label="Password"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入密码!",
              },
            ]}
          >
            <Input.Password prefix={<LockOutlined/>} placeholder="请输入密码"/>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 6,
            }}
          >
            <Link to="/register">还没账号？立即注册</Link>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 11,
              span: 16,
            }}
          >
            <Button size="large" type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
